package com.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 *使用redisTemplate，操作redis
 */
@RestController
public class RedisTemplateTestController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/set")
    public ResponseEntity<String> set(@RequestParam String key, @RequestParam String value) {
        // 处理POST请求逻辑，将参数存储到Redis中
            redisTemplate.opsForValue().set(key, value);
        return ResponseEntity.ok("OK");
    }

    @GetMapping("/get/{key}")
    public ResponseEntity<String> get(@PathVariable String key) {
        // 处理GET请求逻辑，从Redis中获取指定键的值
        String value = redisTemplate.opsForValue().get(key);
        if (value != null) {
            return ResponseEntity.ok(value);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/delete/{key}")
    public ResponseEntity<String> delete(@PathVariable String key) {
        // 处理DELETE请求逻辑，删除Redis中指定的键值对
        Boolean deleted = redisTemplate.delete(key);
        if (deleted) {
            return ResponseEntity.ok("Deleted successfully");
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
